import axios from "axios";
import qs from "qs";
import env from "./env";
import { goLoginPage } from "@/utils/tools";
import { message } from "ant-design-vue";

/**
 * axios发送前和发送后的loading和message.error的统一处理
 * 业务代码中，不需要加loading相关代码
 */
class CustomAxios {
  private msg: any;
  private requestTotal = 0;
  private loading: any;

  public beforeSend() {
    if (this.requestTotal === 0) {
      message.destroy();
      this.msg = null;
      this.loading = message.loading("正在加载...", 0);
    }

    if (this.requestTotal >= 0) {
      this.requestTotal++;
    }
  }

  public afterSend(res?: any) {
    if (this.requestTotal > 0) {
      this.requestTotal--;
    }

    if (this.requestTotal === 0) {
      this.loading();
    }

    if (res && res.config.responseType !== "blob" && res.data.code !== 200 && !this.msg) {
      if (res.data.code === 401) {
        this.msg = message.error("认证失败，无法访问系统资源");
      } else if (res.data.code === 403) {
        this.msg = message.error("当前操作没有权限");
      } else if (res.data.code === 404) {
        this.msg = message.error("访问资源不存在");
      } else {
        this.msg = message.error(res.data.msg);
        // this.msg = message.error("系统未知错误，请反馈给管理员");
      }
    }
  }
}
const customAxios = new CustomAxios();

axios.interceptors.request.use(
  (config: any) => {
    if (!/^http:\/\//.test(config.url)) {
      if (!env.enableProxy) {
        config.url = `${env.apiHost}${config.url}`;
      } else if (env.enableProxy) {
        config.url = `${process.env.VUE_APP_API_PREFIX}${config.url}`;
      }
    }

    // POST前，对数据重组成form格式

    if (!/application\/json/.test(config.headers["Content-Type"]) && config.headers["Content-Type"] !== "multipart/form-data") {
      config.transformRequest = (data: any) => {
        return qs.stringify(data);
      };
    }

    /**
     * 如果不想添加Authorization标识，请在接口参数传入{token: false}
     */
    const data = config.data ? config.data : config.params;
    const token = localStorage.getItem("token");
    // if (token && ((!config.data || config.data.token !== false) || (!config.params || config.params.token !== false))) {
    if (token && (!data || data.token !== false)) {
      config.headers.Authorization = "Bearer " + token;
    }

    if (config.data && config.data.token !== void 0) {
      delete config.data.token;
    }

    if (config.params && config.params.token !== void 0) {
      delete config.params.token;
    }

    customAxios.beforeSend();
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  (response: any) => {
    customAxios.afterSend(response);
    if (response.status === 200) {
      const goLoginCode: number[] = [401];
      if (goLoginCode.indexOf(response.data.code) > -1) {
        goLoginPage();
      } else {
        if (response.data.code === 200) {
          return response.data;
        }
      }
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  (error: any) => {
    customAxios.afterSend({ code: -9999, data: { msg: "请求异常" } });
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 返回 401 清除token信息并跳转到登录页面
          goLoginPage();
          break;
      }
    }
    return Promise.reject(error);
  }
);

export default axios;
